<template>
    <div class="authority">
        <div class="gva-search-box">
            <el-form ref="searchForm" :inline="true">
                <el-form-item label="行政区划">
                    <el-cascader style="width: 90%" :options="areaList" :props="props1" v-model="searchPids"
                        @change="searchAreaChange" />
                </el-form-item>
                <el-form-item label="土地权属类别">
                    <el-select v-model="searchInfo.ownershipType" placeholder="请选择" style="width:160px">
                        <el-option v-for="item in tdqsList" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="办公区名称">
                    <el-input v-model="searchInfo.name" placeholder="请输入" style="width:160px" />
                </el-form-item>
                <el-form-item label="办公区地址">
                    <el-input v-model="searchInfo.address" placeholder="请输入" style="width:160px" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="search" @click="onSubmit">
                        查询
                    </el-button>
                    <el-button icon="refresh" @click="onReset">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="gva-table-box unit">
            <div class="gva-btn-list">
                <el-button type="primary" icon="plus" @click="addUnit">新增办公区</el-button>
            </div>
            <div class="ant-alert-info">
                <el-popover placement="left-start" :width="350" trigger="click" transition='el-zoom-in-left'>
                    <div class="pop-content">
                        <div class="pop-title">自定义列</div>
                        <div class="check-list">
                            <el-checkbox-group v-model="checkedColumns" @change="handleColumnsChange">
                                <el-checkbox v-for="column in columns" :value="column" :label="column"></el-checkbox>
                            </el-checkbox-group>
                        </div>
                    </div>
                    <template #reference>
                        <div class="anticon">
                            <el-icon size="16" color="#1890ff">
                                <Setting />
                            </el-icon>
                            <div style="margin-left: 2px;">自定义列</div>
                        </div>
                    </template>
                </el-popover>
            </div>
            <el-table :data="tableData" row-key="id">
                <el-table-column align="left" label="办公区名称" prop="name" show-overflow-tooltip
                    v-if="checkedColumns.includes('办公区名称')"></el-table-column>
                <el-table-column align="left" label="占地面积(平方米)" prop="coverArea"
                    v-if="checkedColumns.includes('占地面积(平方米)')"></el-table-column>
                <el-table-column align="left" label="办公区地址" prop="address" show-overflow-tooltip
                    v-if="checkedColumns.includes('办公区地址')"></el-table-column>
                <el-table-column align="left" label="行政区划" prop="administrative"
                    v-if="checkedColumns.includes('行政区划')"></el-table-column>
                <el-table-column align="left" label="土地权属类别" v-if="checkedColumns.includes('土地权属类别')">
                    <template #default="scope">
                        <span>{{ scope.row.ownershipType == 1 ? '独立权属' : '多个权属' }}</span>
                    </template>
                </el-table-column>
                <el-table-column align="left" label="楼宇数" prop="buildingNums"
                    v-if="checkedColumns.includes('楼宇数')"></el-table-column>
                <el-table-column align="left" label="宗地图" v-if="checkedColumns.includes('宗地图')">
                    <template #default="scope">
                        <el-image style="width: 70px; height: 70px" :src="scope.row.map" v-if="scope.row.map"
                            :preview-src-list="[scope.row.map]" :preview-teleported="true" </el-image>
                    </template>
                </el-table-column>
                <el-table-column align="left" fixed="right" label="操作" min-width="70"
                    v-if="checkedColumns.includes('操作')">
                    <template #default="scope">
                        <el-button type="primary" link icon="edit" @click="editUnit(scope.row)">
                            编辑
                        </el-button>
                        <el-button type="danger" link icon="delete" @click="delUnit(scope.row)">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="gva-pagination">
                <el-pagination v-model:current-page="page" :page-size="pageSize" :total="total"
                    layout="prev, pager, next" @current-change="handleCurrentChange" />
            </div>
        </div>
        <el-drawer v-model="dialogFormVisible" :size="appStore.drawerSize" :before-close="handleClose"
            :show-close="false">
            <template #header>
                <div class="flex justify-between items-center">
                    <span class="text-lg">{{ dialogTitle }}</span>
                    <div>
                        <el-button @click="closeDialog"> 取 消 </el-button>
                        <el-button type="primary" @click="enterDialog"> 确 定 </el-button>
                    </div>
                </div>
            </template>
            <el-form v-if="dialogFormVisible" ref="bangongquForm" label-width="150" :model="form" :rules="rules">
                <el-form-item label="办公区名称" prop="name">
                    <el-input v-model="form.name" placeholder="请输入" style="width:400px;" />
                </el-form-item>
                <el-form-item label="办公区地址" prop="address">
                    <el-input v-model="form.address" placeholder="请输入" style="width:400px;" />
                </el-form-item>
                <el-form-item label="占地面积" prop="coverArea">
                    <el-input v-model="form.coverArea" placeholder="请输入" style="width:400px;" /><span
                        style="margin-left: 4px;">平方米</span>
                </el-form-item>
                <el-form-item label="行政区划" prop="administrative">
                    <el-cascader style="width: 400px" :options="areaList" :props="props1" v-model="pids"
                        @change="areaChange" />
                </el-form-item>
                <el-form-item label="土地权属类别" prop="ownershipType">
                    <el-select v-model="form.ownershipType" placeholder="请选择" style="width: 400px">
                        <el-option v-for="item in tdqsList" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="权属登记情况" prop="ownership" v-if="qsdjList[form.ownership-1]">
                    <el-input :value="qsdjList[form.ownership-1].name||''" disabled style="width: 400px;" />
                </el-form-item>
                <el-form-item label="建设年代" prop="createYear" v-if="form.createYear">
                    <el-input v-model="form.createYear" disabled style="width: 400px;" />
                    <span style="margin-left: 4px">年</span><span
                        style="margin-left: 10px;color: #FF473E;">注：请按主楼情况填写</span>
                </el-form-item>
                <el-form-item label="是否租用" prop="rent" v-if="form.rent">
                    <el-radio-group v-model="form.rent" class="ml-4" disabled>
                        <el-radio :value="2" size="large">否</el-radio>
                        <el-radio :value="1" size="large">是</el-radio>
                    </el-radio-group>
                    <span style="margin-left: 4px;color: #FF473E;">注：请按主楼情况填写</span>
                </el-form-item>
                <el-form-item label="宗地图">
                    <el-upload v-model:file-list="fileList" :action="adminUrl" :on-success="uploadSuccess"
                        :headers="headerOdj" list-type="picture-card">
                        <el-icon>
                            <Plus />
                        </el-icon>
                        <template #file="{ file }">
                            <div>
                                <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                                <span class="el-upload-list__item-actions">
                                    <span class="el-upload-list__item-delete" @click="handleRemove(file)">
                                        <el-icon>
                                            <Delete />
                                        </el-icon>
                                    </span>
                                </span>
                            </div>
                        </template>
                    </el-upload>
                </el-form-item>
                <el-form-item label="全景链接" prop="panorama">
                    <el-input v-model="form.panorama" style="width: 400px;" />
                </el-form-item>
                <el-form-item label="备注" prop="notes">
                    <el-input v-model="form.notes" type="textarea" style="width: 400px;" />
                </el-form-item>
            </el-form>
        </el-drawer>
    </div>
</template>
<script setup>
import {
    getBgqList,
    deleteBgq,
    createBgq,
    updateBgq
} from '@/api/shujuchuli'
import {
    getRegionList
} from '@/api/unit'
import { reactive, ref, onMounted } from 'vue'
import { useAppStore } from "@/pinia";
import { useUserStore } from '@/pinia/modules/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import { qsdjList } from '@/utils/constant'
defineOptions({
    name: 'Bangonglou'
})
const appStore = useAppStore()
const defaultProps = {
    children: 'children',
    label: 'name',
}

const form = ref({
    address: '',
    administrative: '',
    coverArea: '',
    createYear: '',
    map: '',
    name: '',
    notes: '',
    ownership: '',
    ownershipType: '',
    panorama: '',
    rent: ''
})

const searchInfo = ref({
    address: '',
    administrative: '',
    name: '',
    ownershipType: ''
})

const userStore = useUserStore()
const headerOdj = ref({ token: userStore.token })
const adminUrl = ref('')
adminUrl.value = import.meta.env.VITE_BASE_PATH + '/file/upload'
const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const dialogFormVisible = ref(false)
const rules = reactive({
    name: [{ required: true, message: '请输入办公区名称', trigger: 'blur' }],
    address: [{ required: true, message: '请输入办公区地址', trigger: 'blur' }],
    coverArea: [{ required: true, message: '请输入占地面积', trigger: 'blur' }],
    administrative: [{ required: true, message: '请选择行政区划', trigger: 'change' }],
    ownershipType: [{ required: true, message: '请选择土地权属类别', trigger: 'change' }]
})

const bangongquForm = ref(null)

const pids = ref([])
const props1 = {
    checkStrictly: true,
    label: 'name',
    value: 'name'
}
const initForm = () => {
    bangongquForm.value.resetFields()
    form.value = {
        address: '',
        administrative: '',
        coverArea: '',
        createYear: '',
        map: '',
        name: '',
        notes: '',
        ownership: '',
        ownershipType: '',
        panorama: '',
        rent: ''
    }
    fileList.value = []
    pids.value = []
}
const tdqsList = ref([{ name: '独立权属', id: 1 }, { name: '多个权属', id: 2 }])
const checkedColumns = ref(['办公区名称', '占地面积(平方米)', '办公区地址', '行政区划', '土地权属类别', '楼宇数', '宗地图', '操作'])
if (localStorage.getItem('columnData') && JSON.parse(localStorage.getItem('columnData')).bangongqu) {
    checkedColumns.value = JSON.parse(localStorage.getItem('columnData')).bangongqu
}
const columns = ref(['办公区名称', '占地面积(平方米)', '办公区地址', '行政区划', '土地权属类别', '楼宇数', '宗地图', '操作'])
const handleColumnsChange = (val) => {
    let obj = {

    }
    if (localStorage.getItem('columnData')) {
        obj = JSON.parse(localStorage.getItem('columnData'))
    }
    obj.bangongqu = val
    localStorage.setItem('columnData', JSON.stringify(obj))
}
const isEdit = ref(false)
const dialogTitle = ref('新增办公区')
const addUnit = () => {
    dialogTitle.value = '新增办公区'
    isEdit.value = false
    dialogFormVisible.value = true
}
const closeDialog = () => {
    initForm()
    dialogFormVisible.value = false
}

const handleClose = (done) => {
    initForm()
    done()
}

const handleCurrentChange = (val) => {
    page.value = val
    getTableData()
}
const tableData = ref([])
// 查询
const getTableData = async () => {
    const res = await getBgqList({
        pageNumber: page.value,
        pageSize: pageSize.value,
        ...searchInfo.value
    })
    if (res.code == 200) {
        tableData.value = res.result.data
        total.value = res.result.total
    }
}
getTableData()
const areaList = ref([])

onMounted(() => {
    getRegionList().then(res => {
        areaList.value = res.result
    })
})

const enterDialog = async () => {
    bangongquForm.value.validate(async (valid) => {
        if (valid) {
            let res
            if (isEdit.value) {
                res = await updateBgq(form.value)
            } else {
                form.value.createYear = 0
                form.value.rent = 0
                res = await createBgq(form.value)
            }
            if (res.code == 200) {
                ElMessage({
                    type: 'success',
                    message: isEdit.value ? '编辑成功' : '添加成功!'
                })
                getTableData()
            }
            initForm()
            dialogFormVisible.value = false
        }
    })
}

const delUnit = (row) => {
    ElMessageBox.confirm(
        '确认删除?',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(async () => {
        const res = await deleteBgq(row.id)
        if (res.code === 200) {
            ElMessage({
                type: 'success',
                message: '删除成功!'
            })
            getTableData()
        }
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '已取消删除'
        })
    })
}

const editUnit = async (row) => {
    isEdit.value = true
    dialogTitle.value = '编辑办公区'
    form.value = JSON.parse(JSON.stringify(row))
    if (row.administrative) {
        pids.value = getPids(row.administrative)
    }
    if (form.value.map) {
        fileList.value = [{
            name: '1',
            url: form.value.map
        }]
    }
    //form.value.createYear = form.value.createYear == 0 ? '' : form.value.createYear
    form.value.areaId = form.value.id
    dialogFormVisible.value = true
}
function getPids(val) {
    let res = []
    areaList.value.forEach(m => {
        if (m.name == val) {
            res.push(val)
        }
        if (m.children) {
            m.children.forEach(n => {
                if (n.name == val) {
                    res.push(m.name, n.name)
                }
                if (n.children) {
                    n.children.forEach(o => {
                        if (o.name == val) {
                            res.push(m.name, n.name, o.name)
                        }
                    })
                }
            })
        }
    })
    return res
}
const areaChange = (val) => {
    form.value.administrative = val[val.length - 1]
}
const searchAreaChange = (val) => {
    searchInfo.value.administrative = val[val.length - 1]
}
const onSubmit = () => {
    page.value = 1
    getTableData()
}

const searchPids = ref([])
const onReset = () => {
    searchInfo.value = {
        address: '',
        administrative: '',
        name: '',
        ownershipType: ''
    }
    searchPids.value = []
    getTableData()
}

const fileList = ref([])
const handleRemove = (file) => {
    fileList.value = []
    bangongquForm.value.personalSignature = ''
}
const uploadSuccess = (res) => {
    if (res.code != 200) {
        ElMessage({
            type: 'warning',
            message: res.message
        })
        fileList.value.pop()
        return
    }
    form.value.map = res.result
}

</script>

<style lang="scss">
.flex {
    .area {
        flex: 2;
        background-color: #fff;
        margin: 0.5rem 20px 0.5rem 0;
    }

    .unit {
        flex: 4;
    }
}

.ant-alert-info {
    display: flex;
    justify-content: end;
    align-items: center;
    background-color: #e6f7ff;
    border: 1px solid #91d5ff;
    color: #1890ff;
    padding: 5px;

    .anticon {
        display: flex;
        align-items: center;
        cursor: pointer;
    }
}

.pop-content {
    .pop-title {
        font-weight: bold;
        padding-bottom: 4px;
        border-bottom: 1px solid rgba(5, 5, 5, 0.06);
    }

    .el-checkbox-group {
        font-size: 0;
        line-height: 0;
        display: flex;
        flex-wrap: wrap;
    }
}
</style>